In [1]:
3+5
Out[1]:
In [2]:
3*6
Out[2]:
In [5]:
7 // 4
Out[5]:
In [6]:
x = 5
In [7]:
x*6
Out[7]:
In [8]:
y = x
In [9]:
x = x*2
In [21]:
m = 12
v = 3.8
E = 1/2*m*v**2
print('Energy {}*{}^2/2 = {} '.format(m, v, E))
In [26]:
import math
math.sqrt(2)
math.pow(3, 2.3)
Out[26]:
In [30]:
print(1, math.sqrt(1))
print(2, math.sqrt(2))
print(3, math.sqrt(3))
print(4, math.sqrt(4))
Computes $y = \sqrt{x}$
In [34]:
# My comment
for i in range(1,11):
print(i, math.sqrt(i))
In [1]:
for i in range(1,11):
for j in range(1,11):
print(i*j, end=' ')
print()
In [47]:
for i in range(2,41):
print(i/2, (i/2)**2, (i/2)**3, end="")
In [54]:
x_2 = 0
x_1 = 1
print(x_1, end="\n")
for i in range(3):
y = x_1 + x_2
print(x_2, x_1, y, end="\n")
x_2 = x_1
x_1 = y
In [5]:
import math
r = 0.24
T = 13
S0 = 100
for i in range(T):
print(i, S0*math.exp(r*i/12))
In [8]:
import matplotlib.pylab as plt
r = 0.24
T = 130
S0 = 100
S = [S0*math.exp(r*i/12) for i in range(T)]
plt.plot(range(T), S, 'o-')
plt.xlabel('month')
plt.show()
In [12]:
plt.plot([1,2,5],'ro-')
plt.show()
In [13]:
[2*i for i in range(6)]
Out[13]:
In [14]:
[i*i for i in [j*j for j in [0,1,2]]]
Out[14]:
In [16]:
[[j for j in range(i)] for i in range(5)]
Out[16]:
In [17]:
[[j,j**2,j**3] for j in range(10)]
Out[17]:
$\pi\alpha \frac{3}{\eta}$
In [25]:
plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.unicode'] = True
TH = [th/360*2*math.pi for th in range(-360,361)]
s = [math.sin(th/360*2*math.pi) for th in range(-360,361)]
c = [math.cos(th/360*2*math.pi) for th in range(-360,361)]
plt.plot(TH, s, 'r')
plt.plot(TH, c, 'b')
plt.xticks([-2*math.pi, 0, 2*math.pi],[r'$2\pi$','$0$','$2\pi$'])
plt.show()
In [38]:
import numpy as np
[np.random.randn() for i in range(100)]
Out[38]:
In [2]:
import numpy as np
import matplotlib.pylab as plt
plt.plot(np.random.randn(100))
plt.show()
In [5]:
x = np.random.randn(10000)
plt.hist(x, bins=200)
plt.show()
In [8]:
x = [2,3,7,9]
sum = 0.
for i in range(len(x)):
sum+= x[i]
print(sum/len(x))
In [1]:
Sum = 0.
for e in x:
Sum += e
print(Sum/len(x))
In [10]:
sig = 0.5
N = 100
L = 10
e = [sig*np.random.randn() for i in range(N)]
x = [0]*N
for i in range(N-1):
x[i+1] = x[i] + e[i]
y = [0]*N
for i in range(N):
y[i] = np.mean(x[max(i-L,0):(i+1)])
plt.plot(x)
plt.plot(y, 'r')
plt.show()
Algorithmic trade
In [46]:
%matplotlib inline
plt.figure(figsize=(12,5))
L = 30 # Moving average window
N = 500 # Number of timesteps
# Generate Gaussian noise
e = np.random.randn(N)
# Brownian walk
y = np.zeros_like(e)
y[0] = e[0]
for t in range(1,N):
y[t] = y[t-1] + e[t]
mav = np.zeros_like(e)
for t in range(1,N):
idx0 = max(0, t-L)
mav[t] = np.sum(y[idx0:t])/L
#print(len(y[idx0:t]))
buy = []
sell = []
for t in range(1,N):
if y[t-1]<mav[t-1] and y[t]>mav[t]:
buy.append(t)
if y[t-1]>mav[t-1] and y[t]<mav[t]:
sell.append(t)
plt.plot(y)
plt.plot(mav)
plt.plot(sell, mav[sell],'vr')
plt.plot(buy,mav[buy], '^b')
plt.show()
In [28]:
e[1:8]
Out[28]:
In [42]:
v = [0,1,2,3,4,5]
v[-1:-6:-2]
Out[42]:
In [112]:
a = 5
b = 6
mu = 1
sig = 3
N = 100000
z = mu + sig*np.random.randn(N)
#plt.hist(z, bins=50)
#plt.show()
count = 0
for i in range(N):
if z[i]>=a and z[i]<=b:
count+=1
print(count/N)
In [113]:
import numpy as np
np.log(5)
Out[113]:
European
In [164]:
S0 = 100
r = 0.1
T = 1
sigma = 0.5
K = 120
Num = 10000
opt = 'Put'
#opt = 'Call'
C_T = 0.0
for i in range(Num):
S_T = S0*np.exp(T*(r - 0.5*sigma**2) + sigma*np.sqrt(T)*np.random.randn())
if opt=='Call':
C_T += np.max([S_T-K,0])
else:
C_T += np.max([K-S_T,0])
C_T = C_T/Num
print('{}:'.format(opt), np.exp(-r*T)*C_T)
Asian
In [151]:
S0 = 100
r = 0.1
T = 1
sigma = 0.05
K = 90
N = 100
Num = 10000
C_T = 0.0
for i in range(Num):
S = [0]*N
S[0] = S0
for n in range(1,N):
S[n] = S[n-1]*np.exp(T/N*(r - 0.5*sigma**2) + sigma*np.sqrt(T/N)*np.random.randn())
C_T += np.max([np.mean(S)-K,0])
C_T = C_T/Num
print('Asian Call:', np.exp(-r*T)*C_T)
Lookback
In [153]:
S0 = 100
r = 0.1
T = 1
sigma = 0.05
K = 90
N = 10
Num = 10000
C_T = 0.0
for i in range(Num):
S = [0]*N
S[0] = S0
for n in range(1,N):
S[n] = S[n-1]*np.exp(T/N*(r - 0.5*sigma**2) + sigma*np.sqrt(T/N)*np.random.randn())
C_T += np.max([np.max(S)-K,0])
C_T = C_T/Num
print('Lookback Call:', np.exp(-r*T)*C_T)
Floating Lookback
In [154]:
S0 = 100
r = 0.1
T = 1
sigma = 0.05
K = 90
N = 10
Num = 10000
C_T = 0.0
for i in range(Num):
S = [0]*N
S[0] = S0
for n in range(1,N):
S[n] = S[n-1]*np.exp(T/N*(r - 0.5*sigma**2) + sigma*np.sqrt(T/N)*np.random.randn())
C_T += np.max([S[-1]-np.min(S),0])
C_T = C_T/Num
print('Floating Lookback Call:', np.exp(-r*T)*C_T)
In [166]:
x = -3.7
if x<0:
z = -1
else:
z = 1
z = -1 if x<0 else 1
In [167]:
z
Out[167]:
In [169]:
[i*2 for i in range(5)]
i = 0
while i<10:
i+=2
print(i)
In [171]:
import cmath
cmath.phase(1+2j)
Out[171]:
In [172]:
1+3j + 2-5j
Out[172]:
In [202]:
L = [['c',1], ['z',2], ['a',2]]
L.sort(key=lambda x: x[1])
print(L)
#L.sort(key=lambda x: x[0])
#print(L)
In [184]:
L
Out[184]:
In [204]:
f = open('grades.txt')
N = int(f.readline())
L = []
for i in range(N):
name = str(f.readline()).rstrip()
grade = float(f.readline())
#print(name, grade)
L.append([name, grade])
L.sort(key=lambda x:x[0])
L.sort(key=lambda x:x[1])
#print(L)
if len(L)<1:
print('')
else:
i = 0
for z in L:
if i==0:
mn = z[1]
if mn<z[1]:
break
else:
i+=1
temp = L[i][1]
for j in range(i, len(L)):
if temp<L[j][1]:
break
else:
print(L[j][0])
f.close()
In [205]:
L
Out[205]:
In [ ]:
USD 5.48
GBP 6.99
EUR 6.22
In [2]:
import pandas as pd
In [4]:
aapl = pd.read_csv("aapl.csv", index_col=0, parse_dates=True)
In [5]:
aapl
Out[5]:
In [9]:
import pandas as pd
import pandas_datareader as web
import datetime
start = datetime.datetime(2015, 1, 1)
end = datetime.datetime(2018, 11, 5)
msft = web.DataReader("MSFT", 'yahoo', start, end)
aapl = web.DataReader("AAPL", 'yahoo', start, end)
In [10]:
intl = web.DataReader("INTL", 'yahoo', start, end)
In [12]:
bist = web.DataReader("XU100.IS", 'yahoo', start, end)
In [13]:
bist
Out[13]:
In [11]:
intl
Out[11]:
In [8]:
aapl
Out[8]:
In [18]:
import matplotlib.pylab as plt
plt.figure(figsize=(12,3))
aapl['Close'].plot()
plt.show()
In [28]:
cols = ['Open', 'Close', 'Low', 'High', 'Volume']
for c in cols:
plt.figure(figsize=(12,1))
aapl['2015-08'][c].plot()
plt.show()
In [25]:
aapl['2015-8-21':'2015-10-11']
Out[25]:
In [29]:
dates = ['2015-08','2016-08','2017-08','2018-08']
for d in dates:
plt.figure(figsize=(12,1))
aapl[d]['Open'].plot()
plt.show()
In [44]:
%matplotlib inline
aapl['2017-08'][['High','Low','Close']].plot();
In [48]:
aapl.plot(x='Volume', y='Close', kind='scatter')
Out[48]:
In [53]:
df = pd.DataFrame({'a':[1,2,5],'b':[3, 9, 16], 'c':[10,11,12]},index=[1,2,3])
In [58]:
df.plot.bar();
In [74]:
df.plot.pie(subplots=True);
In [71]:
aapl.plot.hexbin(x='Volume',y='Open')
Out[71]:
In [68]:
aapl['Open'].plot.hist(bins=200)
aapl['Open'].plot.density()
Out[68]:
In [77]:
df[df.b % 2 == 0]
Out[77]:
In [82]:
aapl.iloc[1:100:2]
Out[82]:
In [89]:
df.loc[:,'b':'c']
Out[89]:
In [91]:
df2 = pd.DataFrame({'a':[7,-1,3,5],'b':[1, 1, 1,1], 'c':[10,11,12,18]},index=[7,9,15,18])
In [95]:
df3 = pd.concat([df, df2])
In [97]:
df3[df3.a>=0]
Out[97]:
In [104]:
aapl['Volume'][aapl.High - aapl.Low > 3].plot(style='.');
In [2]:
import math
def circle_area(radius):
return radius**2*math.pi
circle_area(radius=1)
Out[2]:
In [3]:
def rect_area(height, width):
return height*width
In [4]:
rect_area(width=3, height=2)
Out[4]:
Finding the root of a function
In [7]:
def f(x):
return x**2 - 2
def sgn(x):
return 1 if x>0 else -1
def find_root(a, b, epsilon=0.0000001):
left = f(a)
right = f(b)
sgn_l = sgn(left)
sgn_r = sgn(right)
if sgn_l == sgn_r:
error('No root in the interval')
while (right-left>epsilon):
mid = (right+left)/2
f_mid = f(mid)
sgn_mid = sgn(f_mid)
if sgn_l==sgn_mid:
left = mid
else:
right = mid
print(left, right)
return (right+left)/2
print(find_root(1,3))
print(math.sqrt(2))
In [14]:
import matplotlib.pylab as plt
import numpy as np
def f(x):
return x**2 - 2
def sgn(x):
return 1 if x>0 else -1
def find_root(a, b, epsilon=0.0000001):
left = a
right = b
A = [left]
B = [right]
sgn_l = sgn(left)
sgn_r = sgn(right)
if sgn_l == sgn_r:
error('No root in the interval')
while (right-left>epsilon):
mid = (right+left)/2
f_mid = f(mid)
sgn_mid = sgn(f_mid)
if sgn_l==sgn_mid:
left = mid
A.append(left)
else:
right = mid
B.append(right)
#print(left, right)
return A, B
x = np.linspace(-3,3)
plt.plot(x, f(x), 'k-')
A, B = find_root(0, 3)
plt.plot(A, np.zeros_like(A), 'ro')
plt.plot(B, np.zeros_like(B), 'bo')
for a in A:
plt.plot([a, a], [0, f(a)], ':r')
for b in B:
plt.plot([b, b], [0, f(b)], ':b')
plt.show()
In [10]:
B
Out[10]:
In [8]:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
In [3]:
x = [1,2,5,8,1,3,5]
for i in range(len(x)):
x[i] = x[i]*3
x
Out[3]:
In [5]:
x = [z*3 for z in x]
In [9]:
x = np.array([1,2,5,8,1,3,5])
x*3
Out[9]:
In [ ]:
1 2
2 5
5 8
8 1
1 3
3 5
In [12]:
for i in range(len(x)-1):
for j in range(2):
print(x[i+j], end=' ')
print('')
1 2 2 5 5 8 8 1 1 3 3 5
In [20]:
N = 4
for i in range(len(x)-N+1):
for j in range(N):
print(x[i+N-1-j], end=' ')
print('')
Binary Search
In [27]:
L = [1,3,4,7,8,9,12]
i = 0
j = len(L)-1
x = 12
found = False
while (i<=j):
mid = (i+j)//2
if L[mid]==x:
found = True
break
elif L[mid]<x:
i = mid+1
elif L[mid]>x:
j = mid-1
if found:
print('Found')
else:
print('Not Found')